package com.timk.goserver.client.sgf;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.timk.goserver.client.compatibility.Point;

/**
 * Utilities for working with SGF.
 * @author TKington
 *
 */
public class SGFUtils {
	/**
	 * Converts a character to the corresponding coordinate value.
	 * @param chr the character
	 * @return the int coordinate
	 */
    private static int charToNum(char chr) {
        if(chr >= 'a' && chr <= 'z') {
			return chr - 'a';
		}
        return chr - 'A';
    }
    
    /**
     * Converts a string like ac to a Point.
     * @param str the string
     * @return the Point
     * @throws SGFParseException
     */
    public static Point stringToPoint(String str) throws SGFParseException {
        if(str.length() != 2) {
			throw new SGFParseException("Invalid coordinates" + " \""
                                        + str + "\" " + "in sgf file");
		}
        return new Point(charToNum(str.charAt(0)), charToNum(str.charAt(1)));
    }

    /**
     * Converts x,y coordinates to a string like bd
     * @param point the Point
     * @param buf the string is appended to this StringBuffer
     */
	public static void pointToString(Point point, StringBuffer buf) {
		buf.append((char)('a' + point.x));
		buf.append((char)('a' + point.y));
	}
	
	/**
	 * Converts a String of the form &quot;ab cc&quot; to a List&lt;Point&gt;
	 * @param str the String
	 * @return List&lt;Point&gt;
	 */
	public static List stringToPoints(String str) {
		List list = new ArrayList();
		
		if(str.length() > 0) {
			String [] points = str.split(" ");
			for(int j = 0; j < points.length; j++) {
				try {
					list.add(SGFUtils.stringToPoint(points[j]));
				}
				catch(SGFParseException e) {
					break;
				}
			}
		}
		
		return list;
	}
	
	/**
	 * Converts a List&lt;Point&gt; to a String of the form &quot;ab cc&quot; 
	 * @param points List&lt;Point&gt;
	 * @return the String
	 */
	public static String pointsToString(Collection points) {
		StringBuffer buf = new StringBuffer();
		for (Iterator iter = points.iterator(); iter.hasNext();) {
			Point point = (Point) iter.next();
			SGFUtils.pointToString(point, buf);
			buf.append(' ');
		}
		
		return buf.toString();
	}
}
